# websocket_tts_server.py
# WebSocket API to receive text and stream audio (PCM) using iflytek_tts_client

from fastapi import FastAPI, WebSocket, WebSocketDisconnect,APIRouter
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from thirdpart.xf_iat.iflytek_tts_client import IflytekTTSClient

# app = FastAPI()

# # 允许跨域访问
# app.add_middleware(
#     CORSMiddleware,
#     allow_origins=["*"],
#     allow_credentials=True,
#     allow_methods=["*"],
#     allow_headers=["*"],
# )
import requests
from datetime import datetime
from settings import settings
import os
import uuid
import base64
from fastapi import APIRouter, HTTPException
from thirdpart.xf_iat.iflytek_tts_client import IflytekTTSClient
from settings import settings
from fastapi.responses import JSONResponse

iflytek_ws_tts_router = APIRouter()


@iflytek_ws_tts_router.websocket("/ws/tts",name ="tts文字转语音 WebSocket接口")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    try:
        while True:
            text = await websocket.receive_text()
            print(f"收到文本: {text}")

            tts_client = IflytekTTSClient(
                app_id=settings.IFLYTEK_APPID,
                api_key=settings.IFLYTEK_APIKEY,
                api_secret=settings.IFLYTEK_APISECRET,
            )

            async for chunk in tts_client.stream_text_to_pcm(text):
                await websocket.send_bytes(chunk)

            await websocket.send_text("[END]")  # 标记结束

    except WebSocketDisconnect:
        print("WebSocket disconnected")
    except Exception as e:
        print("TTS 服务错误：", e)
        await websocket.close(code=1011)






@iflytek_ws_tts_router.post("/tts/url")
async def tts_url(request: dict):
    """
    接收 JSON {"text": "..."}，合成语音并返回 MP3 文件 URL。
    """
    text = request.get("text", "").strip()
    if not text:
        raise HTTPException(status_code=400, detail="text 不能为空")

    # 调用讯飞 WebSocket TTS 客户端
    client = IflytekTTSClient(
        app_id=settings.IFLYTEK_APPID,
        api_key=settings.IFLYTEK_APIKEY,
        api_secret=settings.IFLYTEK_APISECRET,
    )

    # 收集所有 base64 分段
    chunks = []
    try:
        async for b64 in client.stream_text_to_pcm(text):
            chunks.append(b64)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"TTS 合成失败：{e}")

    # 拼接并解码为二进制
    audio_data = base64.b64decode("".join(chunks))

    # 保存到静态目录
    out_dir = os.path.join("music", "tts")
    os.makedirs(out_dir, exist_ok=True)
    filename = f"{uuid.uuid4().hex}.mp3"
    file_path = os.path.join(out_dir, filename)
    with open(file_path, "wb") as f:
        f.write(audio_data)
        # 在生成文件后设置权限
    os.chmod(file_path, 0o644)  # 644 权限：所有者可读写，其他用户可读


    # 返回静态访问 URL
    url = f"/music/tts/{filename}"
    return JSONResponse({"url": url})
# if __name__ == "__main__":
#     uvicorn.run("websocket_tts_server:app", host="0.0.0.0", port=8001, reload=True)
